<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\event;

use app\library\websocket\action\File;
use app\library\websocket\action\MessageCenter;
use app\library\websocket\action\Unknown;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
use think\helper\Str;

class MessageEvent
{
    public static function handle(Server $server, Frame $frame)
    {
        if (!is_null($frame) && $frame->opcode == SWOOLE_WEBSOCKET_OPCODE_TEXT) {
            $data = $frame->data;
            $data = json_decode($data, true);
            $msgType = isset($data['action']) ? $data['action'] : 'unknown';
            $namespace = __NAMESPACE__;
            $namespaceMap = explode('\\', $namespace);
			array_pop($namespaceMap);
            array_push($namespaceMap, 'action', Str::studly($msgType));
            $className = implode('\\', $namespaceMap);
        } elseif (!is_null($frame) && $frame->opcode == SWOOLE_WEBSOCKET_OPCODE_BINARY) {
            $className = File::class;
        } else {
            $className = Unknown::class;
        }
        /**
         * @var MessageCenter $class
         */
        $class = new $className($server, $frame);
        return $class->handle();
    }
}
